package net.wantongtech.xa.uploadbasicinfo.service;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.UploadBasicInfoDao;
import net.wantongtech.xa.uploadbasicinfo.vo.Organization;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 修改错误channelId服务实现
 *
 * @author MaShibo
 * 日期 :  2019/12/18
 */
@Slf4j
@Service
public class AlterOrgChannelIdService {


    @Resource
    private UploadBasicInfoDao uploadBasicInfoDao;


    private Set<String> channelIdSet;

    private static Map<String, String> sourceToMap;


    static {
        sourceToMap = Maps.newHashMapWithExpectedSize(3);
        sourceToMap.put("61010102018", "61010102011");
        sourceToMap.put("61010102005", "61010102007");
        sourceToMap.put("61010102008", "61010102001");
    }


    public void init() {
        channelIdSet = uploadBasicInfoDao.queryAllChannelId();
        log.info("共查询到{}个channelId", channelIdSet.size());
    }

    public void alter() {

        sourceToMap.forEach((source, to) -> {

            List<Organization> organizationList = uploadBasicInfoDao.queryOrganizationByChannelId(source);
            organizationList.forEach(organization -> {

                String channelId = organization.getChannelId();
                String newChannelId = channelId.replace(source, to);
                int length = channelId.length();
                String serialNo = channelId.substring(length - 4, length);
                int serialNoInt = Integer.parseInt(serialNo);
                while (channelIdSet.contains(newChannelId)) {
                    ++serialNoInt;
                    newChannelId = String.format("%s%s", newChannelId.substring(0, length - 4),
                            StringUtils.leftPad(String.valueOf(serialNoInt), 4, '0'));
                }
                log.info("原渠道编号：{}，新渠道编号：{}", channelId, newChannelId);
                channelIdSet.add(newChannelId);
                organization.setChannelId(newChannelId);
                organization.setDescription("update");
                uploadBasicInfoDao.updateObject(organization);
            });

        });
    }

}
